package com.sqx.modules.app.service.impl;

import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.AppUserInfo;
import com.sqx.modules.app.entity.Msg;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.service.PhoneVerificationCodeService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.app.utils.UserConstantInterface;
import com.sqx.modules.chats.utils.ResultUtil;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.entity.Feedback;
import com.sqx.modules.file.utils.Md5Utils;
import com.sqx.modules.integral.dao.UserIntegralDao;
import com.sqx.modules.integral.entity.UserIntegral;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.InvitationCodeUtil;
import com.sqx.modules.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import weixin.popular.api.SnsAPI;
import weixin.popular.util.JsonUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 *
 * @author fang
 * @date 2021/2/27
 */

@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private JwtUtils jwtUtils;
    private int number = 1;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private UserIntegralDao userIntegralDao;

    @Resource
    PhoneVerificationCodeService phoneVerificationCodeService;

    @Autowired
    // 当前运行环境值

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Override
    public UserEntity queryByPhone(String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
        }
        return null;
    }

    @Override
    public UserEntity queryByPhoneAndType(String phone) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
    }

    @Override
    public UserEntity queryByOpenId(String openId, Integer userType) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
    }

    public UserEntity queryByRiderOpenId(String openId, Integer userType) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("rider_open_id", openId));
    }

    @Override
    public UserEntity queryByWxOpenId(String openId, Integer userType) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_open_id", openId).eq("user_type", userType));
    }

    public UserEntity queryWxOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_open_id", openId));
    }

    public UserEntity queryRiderWxOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("rider_wx_open_id", openId));
    }

    @Override
    public UserEntity queryByAppleId(String appleId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("apple_id", appleId));
    }

    @Override
    public UserEntity queryByUserId(Long userId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
    }

    @Override
    public UserEntity queryByInvitationCode(String invitationCode) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", invitationCode));
    }

    @Override
    public Result updatePhone(String phone, String msg, Long userId) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 != null) {
            UserEntity userInfo = queryByPhone(phone);
            if (userInfo != null) {
                return Result.error("手机号已经被其他账号绑定");
            } else {
                UserEntity one = baseMapper.selectById(userId);
                one.setPhone(phone);
                baseMapper.updateById(one);
                return Result.success();
            }
        }
        return Result.error("验证码不正确");
    }

    @Override
    public Result iosRegister(String appleId) {
        if (StringUtils.isEmpty(appleId)) {
            return Result.error("账号信息获取失败，请退出重试！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserEntity userInfo = queryByAppleId(appleId);
        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
            //返回用户信息
            UserEntity user = queryByAppleId(appleId);
            return getResult(user);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }

    @Override
    public Result wxLogin(String code, Integer type) {
        try {
            String appid;
            String secret;
            if (type == 1) {
                appid = commonInfoService.findOne(45).getValue();
                secret = commonInfoService.findOne(46).getValue();
            } else if (type == 2) {
                appid = commonInfoService.findOne(248).getValue();
                secret = commonInfoService.findOne(249).getValue();
            } else {
                appid = commonInfoService.findOne(305).getValue();
                secret = commonInfoService.findOne(306).getValue();
            }
            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", appid);
            param.put("secret", secret);
            param.put("js_code", code);
            param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE);
            param.put("scope", "snsapi_userinfo");
            // 发送请求
            String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param);
            log.info(wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();
            //返回微信小程序openId
            String open_id = jsonObject.get("openid").toString();
            //判断是否注册过
            Map<String, String> map = new HashMap<>();
            // 封装返回小程序
            map.put("session_key", session_key);
            map.put("open_id", open_id);
            //    UserEntity userEntity = null;
            if (type == 1) {
                UserEntity userEntity = queryByOpenId(open_id, type);
                if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) {
                    //存在手机号
                    map.put("isPhone", "1");
                } else {
                    //不存在手机号
                    map.put("isPhone", "2");
                }
            } else if (type == 2) {
                UserEntity userEntity = queryByRiderOpenId(open_id, type);
                if (userEntity != null && StringUtils.isNotEmpty(userEntity.getPhone())) {
                    //存在手机号
                    map.put("isPhone", "1");
                } else {
                    //不存在手机号
                    map.put("isPhone", "2");
                }
            }
            if (jsonObject.get("unionid") != null) {
                String unionid = jsonObject.get("unionid").toString();
                map.put("unionid", unionid);
            } else {
                map.put("unionid", "-1");
            }
            return Result.success("登陆成功").put("data", map);
        } catch (Exception e) {
            System.err.println(e.toString());
            return Result.error("登录失败！");
        }
    }


    @Override
    public Result wxRegister(UserEntity userInfo1) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        //  UserEntity userInfo = queryByOpenId(userInfo1.getOpenId(),userInfo1.getUserType());
        UserEntity userInfo = null;
        if (userInfo1.getUserType() == 1) {
            userInfo = queryByOpenId(userInfo1.getOpenId(), userInfo1.getUserType());
        } else {
            userInfo = queryByRiderOpenId(userInfo1.getRiderOpenId(), userInfo1.getUserType());
        }


        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }

            if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                if (StringUtils.isBlank(userInfo.getPhone())) {
                    userInfo.setPhone(userInfo1.getPhone());
                }

            }
            if(StringUtils.isEmpty(userInfo.getNickName()) || "微信用户".equals(userInfo.getNickName())){
                if(StringUtils.isNotEmpty(userInfo.getPhone())){
                    userInfo.setNickName(userInfo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})","$1****$2"));
                }
            }

            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
        } else {
            if (StringUtils.isEmpty(userInfo1.getPhone())) {
                return Result.error("请先授权手机号！");
            }
            //判断是否在app登陆过  手机号是否有账号
            UserEntity userByMobile = queryByPhone(userInfo1.getPhone());
            if (userByMobile != null) {
                //有账号则绑定账号
                if (userInfo1.getUserType() == 1) {
                    userByMobile.setOpenId(userInfo1.getOpenId());
                } else {
                    userByMobile.setRiderOpenId(userInfo1.getRiderOpenId());
                }
                baseMapper.updateById(userByMobile);

                //数据库消息保存
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("小程序账号绑定成功！");
                messageInfo.setTitle("系统通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userByMobile.getNickName());
                messageInfo.setUserId(String.valueOf(userByMobile.getUserId()));
                messageInfo.setCreateAt(sdf.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                //app消息推送
                if (StringUtils.isNotEmpty(userByMobile.getClientid())) {
                    pushToSingle("系统通知", "小程序账号绑定成功", userByMobile.getClientid());
                }
                if (userByMobile.getStatus().equals(2)) {
                    return Result.error("账号已被封禁，请联系客服处理！");
                }
            } else {
                if (StringUtils.isEmpty(userInfo1.getInviterCode())) {
                    userInfo1.setInviterCode(commonInfoService.findOne(88).getValue());
                }
                //没有则生成新账号
                userInfo1.setCreateTime(date);
                userInfo1.setPlatform("小程序");
                userInfo1.setStatus(1);
                userInfo1.setBalance(BigDecimal.valueOf(0));
                userInfo1.setCashDeposit(BigDecimal.valueOf(0));
                //新用户注册，加新用户标识为1
                userInfo1.setNewUserFlag(1);
                userInfo1.setNewUserFlagWm(1);

                if(StringUtils.isEmpty(userInfo1.getNickName()) || "微信用户".equals(userInfo1.getNickName())){
                    if(StringUtils.isNotEmpty(userInfo1.getPhone())){
                        userInfo1.setNickName(userInfo1.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})","$1****$2"));
                    }
                }

                userInfo1.setIsVip(0);
                baseMapper.insertUser(userInfo1);
                //注册新账号的时候，创建钱包
                UserMoney userMoney = new UserMoney();
                userMoney.setUserId(userInfo1.getUserId());
                userMoney.setMoney(new BigDecimal(0));
                userMoneyDao.insert(userMoney);
                //注册新账号得时候，创建积分仓库
                UserIntegral userIntegral = new UserIntegral();
                userIntegral.setUserId(userInfo1.getUserId());
                userIntegral.setIntegralNum(0);
                userIntegralDao.insert(userIntegral);
                userInfo1.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo1.getUserId()));
                baseMapper.updateById(userInfo1);
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("恭喜您，账号注册成功！");
                messageInfo.setTitle("系统通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userInfo1.getNickName());
                messageInfo.setUserId(String.valueOf(userInfo1.getUserId()));
                messageInfo.setCreateAt(sdf.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
            }
        }
        //返回用户信息
        if (userInfo1.getUserType() == 1) {
            UserEntity user = selectByOpenId(userInfo1.getOpenId());
            return getResult(user);
        } else {
            UserEntity user = selectByRiderOpenId(userInfo1.getRiderOpenId());
            return getResult(user);
        }
    }

    private UserEntity selectByRiderOpenId(String riderOpenId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("rider_open_id", riderOpenId));
    }

    private UserEntity selectByOpenId(String openId) {

        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
    }


    @Override
    public Result wxBindMobile(String phone, String code, String wxOpenId, String token, String platform, Integer sysPhone) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getWxOpenId())) {
                return Result.error("当前手机号已经被其他微信绑定");
            }
            //小程序登陆过
            userInfo.setWxOpenId(wxOpenId);
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            baseMapper.updateById(userInfo);
        } else {
            //小程序没有登陆过
            userInfo = new UserEntity();
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            userInfo.setWxOpenId(wxOpenId);
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            //新用户注册，加新用户标识
            userInfo.setNewUserFlag(1);
            userInfo.setNewUserFlagWm(1);
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryWxOpenId(userInfo.getWxOpenId());
        return getResult(userEntity);
    }

    @Override
    public Result iosBindMobile(String phone, String code, String appleId, String platform, Integer sysPhone) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getAppleId())) {
                return Result.error("当前手机号已经被其他苹果绑定");
            }
            userInfo.setAppleId(appleId);
            userInfo.setUpdateTime(simpleDateFormat.format(new Date()));
            baseMapper.updateById(userInfo);
        } else {
            userInfo = new UserEntity();
            userInfo.setSex(0);
            userInfo.setNickName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryByAppleId(userInfo.getAppleId());
        return getResult(userEntity);
    }


    @Override
    public Result wxAppLogin(String wxOpenId, String token) {
        UserEntity userEntity = queryWxOpenId(wxOpenId);
        if (userEntity != null) {
            if (userEntity.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userEntity.setAvatar(user.getHeadimgurl());
                }
                userEntity.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userEntity.setNickName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userEntity.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userEntity);
            return getResult(userEntity);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }


    @Override
    public Result registerCode(String phone, String msg, String platform, Integer sysPhone, String password, Integer userType, String openId) {
        //登录区分  验证码登录  账号密码登录
        //1.验证码登录  所需参数  phone  msg  platform  userType
        //2.账号密码登录  所需参数  phone  password  platform  userType
        //3.验证码注册  所需参数  phone  password  msg platform userType
        //两者之间的区分 为 是否传递 msg 或者 password  前端传递msg 则为验证码 登录  反之则相反


        UserEntity userInfo = queryByPhoneAndType(phone);
        //校验手机号是否存在   判断当前手机号是否已经注册过了  如果注册过了  则判断是验证码登录还是账号密码登录
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(password)) {
                if (StringUtils.isEmpty(userInfo.getPassword())) {
                    return Result.error("当前账号未设置密码，请使用短信登录或忘记密码去重置密码！");
                }
                //密码登录  判断输入密码加密之后是否和数据库的加密密码相同
                String pwd = DigestUtils.sha256Hex(password);
                if (!userInfo.getPassword().equals(pwd)) {
                    return Result.error("账号或密码不正确！");
                }
            } else {
                //验证码的登录  判断输入的验证码 和发送验证码时存入数据库的验证码是否一致
                Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
                //校验短信验证码
                if (msg1 == null) {
                    return Result.error("验证码不正确");
                }
                msgDao.deleteById(msg1.getId());
            }

            //判断当前手机号是否被管理员封禁
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //更新最新的登录时间
            userInfo.setUpdateTime(sdf.format(new Date()));
            if (userType == 1) {
                userInfo.setWxOpenId(openId);
            } else if (userType == 2) {
                userInfo.setRiderWxOpenId(openId);
            }
            baseMapper.updateById(userInfo);
            //返回登录信息  tokne  用户信息的等
            return getResult(userInfo);
        } else {
            //没有注册过  则注册新的账号
            //注册账号需要先判断当前手机号是否是真实的手机号 则需要校验验证码
            Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
            //校验短信验证码
            if (msg1 == null) {
                return Result.error("验证码不正确");
            }
            msgDao.deleteById(msg1.getId());
            //验证码校验完成  则创建用户

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //设置注册时间
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            //填充前端传递的相关参数
            userInfo.setPhone(phone);
            //添加默认头像
            CommonInfo one = commonInfoService.findOne(232);
            userInfo.setAvatar(one.getValue());
            userInfo.setNickName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPlatform(platform);
            if (StringUtils.isNotEmpty(password)) {
                userInfo.setPassword(DigestUtils.sha256Hex(password));
            }
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            //用户类型
            userInfo.setUserType(userType);
            if (userType == 1) {
                userInfo.setWxOpenId(openId);
            } else if (userType == 2) {
                userInfo.setRiderWxOpenId(openId);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setUpdateTime(sdf.format(new Date()));
            //新用户注册，加新用户标识
            userInfo.setNewUserFlag(1);
            userInfo.setNewUserFlagWm(1);
            //新注册用户钱包余额和保证金为0
            userInfo.setBalance(BigDecimal.valueOf(0));
            userInfo.setCashDeposit(BigDecimal.valueOf(0));
            userInfo.setIsVip(0);
//            baseMapper.insert(userInfo);
            baseMapper.insertUser(userInfo);
            //注册新账号的时候，创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(new BigDecimal(0));
            userMoneyDao.insert(userMoney);
            //注册新账号得时候，创建积分仓库
            UserIntegral userIntegral = new UserIntegral();
            userIntegral.setUserId(userInfo.getUserId());
            userIntegral.setIntegralNum(0);
            userIntegralDao.insert(userIntegral);
            //返回用户tokne 用户信息
            return getResult(userInfo);
        }
    }


    @Override
    public Result wxOpenIdLogin(String openId, Integer userType) {
        UserEntity userEntity;
        if (userType == 1) {
            userEntity = queryWxOpenId(openId);
        } else {
            userEntity = queryRiderWxOpenId(openId);
        }
        if (userEntity != null) {
            return getResult(userEntity);
        }
        return Result.error("未注册！");
    }


    @Override
    public Result login(String phone, String pwd) {
        UserEntity userEntity = queryByPhone(phone);
        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(pwd))) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);
    }


    @Override
    public Result getResult(UserEntity user) {
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", user);
        return Result.success(map);
    }


    @Override
    public Result sendMsg(String phone, String state) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println("sendMsg code is " + code);
        SmsSingleSenderResult result = null;
        /*if ("bindWx".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getWxOpenId())) {
                return Result.error("当前手机号已被其他微信账号绑定");
            }
        } else if ("bindIos".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getAppleId())) {
                return Result.error("当前手机号已被其他苹果账号绑定");
            }
        }*/
        //注册账号传递
        /*if("register".equals(state)){
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null) {
                return Result.error("手机号已经注册过了！");
            }
        }*/
        //登录传递或修改密码时传递
//        if("login".equals(state)){
//            UserEntity userByPhone = queryByPhone(phone);
//            /*if (userByPhone == null) {
//                return Result.error("手机号未注册");
//            }*/
//        }

        // 测试环境
        if (StringUtils.equals(activeProfile,"dev")) {
            phoneVerificationCodeService.updateOrAdd(phone, String.valueOf(code));
            return Result.success("login");
        }

        CommonInfo three = commonInfoService.findOne(79);
        //默认使用腾讯云
        if (three.getValue().equals("1")) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code);
        } else if (three.getValue().equals("2")) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, state, code);
        } else {
            return sendMsgDXB(phone, state, code);
        }
    }

    @Override
    public Result sendMsgDXB(String phone, String state, int code) {
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        CommonInfo one = commonInfoService.findOne(12);
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        String value = "";
        switch (state) {
            case "register":
                value = "【" + one.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "forget":
                value = "【" + one.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "bind":
                value = "【" + one.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "ruzhu":
                value = "【" + one.getValue() + "】验证码: " + code + "，您正在执行入驻操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "autosend":
                value = "【" + one.getValue() + "】系统已为您自动派单，请及时前往派送！";
                break;
            case "chenggong":
                value = "【" + one.getValue() + "】您好，您的商户资料审核成功，已为您注册账号，账号密码均为您的手机号，您可前往商户端登录操作。";
                break;
            case "shibai":
                value = "【" + one.getValue() + "】您好，您提交的商户资料审核失败，请您尽快核对信息或补充资料。";
                break;
            case "jieguo":
                value = "【" + one.getValue() + "】您的入驻申请已提交,请等待审核,最终结果会通过短信通知";
                break;
            case "weigui":
                value = "【" + one.getValue() + "】 您的店铺因违规操作已被封禁，请联系平台客服！";
                break;
            case "selectShop":
                value = "【" + one.getValue() + "】您正在查询商户信息，验证码：" + code + "，如非您本人操作，可忽略本条消息";
                break;
            default:
                value = "【" + one.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
        }

        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值：" + result);

        // todo 短信验证码失效没有进行校验
        if ("0".equals(result)) {
            Msg byPhone = msgDao.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(code));
                byPhone.setPhone(phone);
                msgDao.updateById(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(code));
                msg.setPhone(phone);
                msgDao.insert(msg);
            }
            return Result.success("login");
        } else {
//            return ResultUtil.error(6, result.errMsg);
            if ("30".equals(result)) {
                return Result.error(-200, "错误密码");
            } else if ("40".equals(result)) {
                return Result.error(-200, "账号不存在");
            } else if ("41".equals(result)) {
                return Result.error(-200, "余额不足");
            } else if ("43".equals(result)) {
                return Result.error(-200, "IP地址限制");
            } else if ("50".equals(result)) {
                return Result.error(-200, "内容含有敏感词");
            } else if ("51".equals(result)) {
                return Result.error(-200, "手机号码不正确");
            }
        }

        return Result.error("验证码发送失败！");
    }

    private Result sendMsgAlibaba(String phone, String state, int code) {
        //阿里云短信accessKeyId
        CommonInfo three = commonInfoService.findOne(93);
        String accessKeyId = three.getValue();
        //阿里云短信accessSecret
        CommonInfo four = commonInfoService.findOne(94);
        String accessSecret = four.getValue();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonInfo name = commonInfoService.findOne(12);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", name.getValue());
        String value;
        switch (state) {
            case "register":
                value = commonInfoService.findOne(100).getValue();
                break;
            case "forget":
                value = commonInfoService.findOne(101).getValue();
                break;
            case "bind":
                value = commonInfoService.findOne(102).getValue();
                break;
            case "ruzhu":
                value = commonInfoService.findOne(103).getValue();
                break;
            case "autosend":
                value = commonInfoService.findOne(104).getValue();
                break;
            case "chenggong":
                value = commonInfoService.findOne(105).getValue();
                break;
            case "shibai":
                value = commonInfoService.findOne(106).getValue();
                break;
            case "jieguo":
                value = commonInfoService.findOne(107).getValue();
                break;
            case "weigui":
                value = commonInfoService.findOne(108).getValue();
                break;
            case "selectShop":
                value = commonInfoService.findOne(109).getValue();
                break;
            default:
                value = commonInfoService.findOne(100).getValue();
                break;
        }
        request.putQueryParameter("TemplateCode", value);
        if (!"autosend".equals(state) && !"chenggong".equals(state) && !"shibai".equals(state) && !"jieguo".equals(state) && !"weigui".equals(state)) {
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        }

        try {
            CommonResponse response = client.getCommonResponse(request);
            log.error(response.getData());
            String data = response.getData();
            JSONObject jsonObject = JSON.parseObject(data);
            if ("OK".equals(jsonObject.get("Code"))) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
           /*     UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }*/
                return Result.success("login");
            } else {
                if (jsonObject.get("Message").toString().contains("分钟")) {
                    return Result.error("短信发送过于频繁，请一分钟后再试！");
                } else if (jsonObject.get("Message").toString().contains("小时")) {
                    return Result.error("短信发送过于频繁，请一小时后再试！");
                } else if (jsonObject.get("Message").toString().contains("天")) {
                    return Result.error("短信发送过于频繁，请明天再试！");
                }
                log.info(jsonObject.get("Message").toString());
                return Result.error("短信发送失败！");
            }
        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    private Result sendMsgTencent(String phone, String state, int code) {
        SmsSingleSenderResult result = null;
        try {
            CommonInfo three = commonInfoService.findOne(31);
            String clientId = three.getValue();

            CommonInfo four = commonInfoService.findOne(32);
            String clientSecret = four.getValue();
            CommonInfo name = commonInfoService.findOne(12);
            /**
             * 发送短信验证码的状态、
             *
             * 在h5登录环境中 传的状态不是以下三种状态
             */
            SmsSingleSender ssender = new SmsSingleSender(Integer.parseInt(clientId), clientSecret);
            switch (state) {
                case "register":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "forget":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "bind":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "ruzhu":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行入驻操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "autosend":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】系统已为您自动派单，请及时前往派送！", "", "");
                    break;
                case "chenggong":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您好，您的商户资料审核成功，已为您注册账号，账号密码均为您的手机号，您可前往商户端登录操作。", "", "");
                    break;
                case "shibai":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您好，您提交的商户资料审核失败，请您尽快核对信息或补充资料。", "", "");
                    break;
                case "jieguo":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您的入驻申请已提交,请等待审核,最终结果会通过短信通知", "", "");
                    break;
                case "weigui":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】 您的店铺因违规操作已被封禁，请联系平台客服！", "", "");
                    break;
                case "selectShop":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】您正在查询商户信息，验证码：" + code + "，如非您本人操作，可忽略本条消息", "", "");
                    break;
                default:
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
            }


            System.out.println(result);
            if (result.result == 0) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }
            } else {
                return Result.error(6, result.errMsg);
            }
        } catch (HTTPException | JSONException | IOException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    @Override
    public Result getOpenId(String code, Long userId) {
        try {
            //微信appid
            CommonInfo one = commonInfoService.findOne(5);
            //微信秘钥
            CommonInfo two = commonInfoService.findOne(21);
            String openid = SnsAPI.oauth2AccessToken(one.getValue(), two.getValue(), code).getOpenid();
            if (StringUtils.isNotEmpty(openid)) {
                UserEntity userEntity = new UserEntity();
                userEntity.setUserId(userId);
                userEntity.setOpenId(openid);
                baseMapper.updateById(userEntity);
                return Result.success().put("data", openid);
            }
            return Result.error("获取失败");
        } catch (Exception e) {
            log.error("GET_OPENID_FAIL");
            return Result.error("获取失败,出错了！");
        }
    }

    @Override
    public UserEntity selectUserById(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public int updateUserClientIdIsNull(String clientid) {
        return baseMapper.updateUserClientIdIsNull(clientid);
    }

    @Override
    public int updateUserRiderClientIdIsNull(String clientid) {
        return baseMapper.updateUserRiderClientIdIsNull(clientid);
    }

    @Override
    public int updateUserShopClientIdIsNull(String clientid) {
        return baseMapper.updateUserRiderClientIdIsNull(clientid);
    }

    @Override
    public PageUtils selectUserPage(Integer page, Integer limit, String search, Integer sex, String platform, String sysPhone, Integer status,
                                    Integer type, String userName, Integer isVip, Integer shopAdminFlag, String nickName) {
        Page<UserEntity> pages = new Page<>(page, limit);
        return new PageUtils(baseMapper.selectUserPage(pages, search, sex, platform, sysPhone, status, type, userName, isVip, shopAdminFlag, nickName));
    }

    @Override
    public int queryInviterCount(String inviterCode) {
        return baseMapper.queryInviterCount(inviterCode);
    }

    @Override
    public int queryUserCount(int type, String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        if (date == null || date == "") {
            date = simpleDateFormat.format(new Date());
        }
        return baseMapper.queryUserCount(type, date);
    }

    @Override
    public Double queryPayMoney(int type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        String date = simpleDateFormat.format(new Date());
        return baseMapper.queryPayMoney(type, date);
    }

    @Override
    public IPage<Map<String, Object>> queryCourseOrder(Page<Map<String, Object>> iPage, int type, String date) {
        return baseMapper.queryCourseOrder(iPage, type, date);
    }

    @Override
    public int userMessage(String date, int type) {
        return baseMapper.userMessage(date, type);
    }


    @Override
    public void pushToSingle(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("clientid", clientId));
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                apiConfiguration.setAppId(commonInfoService.findOne(61).getValue());
                apiConfiguration.setAppKey(commonInfoService.findOne(60).getValue());
                apiConfiguration.setMasterSecret(commonInfoService.findOne(62).getValue());
                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    GTNotification notification = new GTNotification();
                    pushDTO.setPushMessage(pushMessage);
                    // 配置通知栏图标
                    notification.setLogo(commonInfoService.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                    // 配置通知栏网络图标
                    notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png");
                    notification.setTitle(title);
                    notification.setBody(content);
                    notification.setClickType("startapp");
                    notification.setUrl(commonInfoService.findOne(19).getValue());
                    notification.setChannelLevel("3");
                    pushMessage.setNotification(notification);
                } else {
                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                }
                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.info("消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("消息推送失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }


    @Override
    public void pushToSingleRider(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("rider_clientid", clientId));
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                apiConfiguration.setAppId(commonInfoService.findOne(58).getValue());
                apiConfiguration.setAppKey(commonInfoService.findOne(57).getValue());
                apiConfiguration.setMasterSecret(commonInfoService.findOne(59).getValue());
                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    GTNotification notification = new GTNotification();
                    pushDTO.setPushMessage(pushMessage);
                    // 配置通知栏图标
                    notification.setLogo(commonInfoService.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                    // 配置通知栏网络图标
                    notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png");
                    notification.setTitle(title);
                    notification.setBody(content);
                    notification.setClickType("startapp");
                    notification.setUrl(commonInfoService.findOne(19).getValue());
                    notification.setChannelLevel("3");
                    pushMessage.setNotification(notification);
                } else {
                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                }
                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.info("消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("消息推送成功失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }


    @Override
    public void pushToSingleShop(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("shop_client_id", clientId));
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                apiConfiguration.setAppId(commonInfoService.findOne(55).getValue());
                apiConfiguration.setAppKey(commonInfoService.findOne(54).getValue());
                apiConfiguration.setMasterSecret(commonInfoService.findOne(56).getValue());
                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    GTNotification notification = new GTNotification();
                    pushDTO.setPushMessage(pushMessage);
                    // 配置通知栏图标
                    notification.setLogo(commonInfoService.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                    // 配置通知栏网络图标
                    notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png");
                    notification.setTitle(title);
                    notification.setBody(content);
                    notification.setClickType("startapp");
                    notification.setUrl(commonInfoService.findOne(19).getValue());
                    notification.setChannelLevel("3");
                    pushMessage.setNotification(notification);
                } else {
                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                }
                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.info("消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("消息推送成功失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }

    @Override
    public Result loginApp(String phone, String password) {
        //md5加密
        String pwd = DigestUtils.sha256Hex(password);
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserEntity userEntity = baseMapper.selectOne(queryWrapper);
        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (!userEntity.getPassword().equals(pwd)) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);

    }


    @Override
    public Result forgetPwd(String pwd, String phone, String msg) {
        try {
            Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, msg);
            //校验短信验证码
            if (byPhoneAndCode == null) {
                return Result.error("验证码不正确");
            }
            UserEntity userByPhone = queryByPhone(phone);
            userByPhone.setPassword(DigestUtils.sha256Hex(pwd));
            msgDao.deleteById(byPhoneAndCode.getId());
            baseMapper.updateById(userByPhone);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @Override
    public Result takingOrdersMessage(Page<Map<String, Object>> iPage, Long type, String date) {
        //接单分析
        return Result.success().put("data", new PageUtils(baseMapper.takingOrdersMessage(iPage, type, date)));
    }

    @Override
    public Result selectUserList(Integer page, Integer limit, String userName) {
        Page<UserEntity> pages = new Page<>(page, limit);

        return Result.success().put("data", new PageUtils(baseMapper.selectUserList(pages, userName)));
    }

    @Override
    public Result selectUserId(String invitationCode) {
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", invitationCode));
        if (userEntity.getUserId() == null) {
            return Result.error("该用户不存在！");
        }
        return Result.success().put("data", userEntity.getUserId());
    }

    @Override
    public Result selectUserMessage(Long userId) {
        UserEntity userEntity = baseMapper.selectUserMessage(userId);
        return Result.success().put("data", userEntity);
    }

    @Override
    public Result updateUserMessage(UserEntity userEntity) {
        return null;
    }

    @Override
    public Result userFeedback(Long userId, Feedback feedback) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        userDao.userFeedback(feedback.getFeedbackType(), userId, feedback.getUserEmail(), feedback.getFeedbackScore(), feedback.getFeedbackMessage(), format);
        return Result.success();
    }

    @Override
    public Result updateShopAdminFlag(Long userId, Integer shopAdminFlag) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        userEntity.setShopAdminFlag(shopAdminFlag);
        baseMapper.updateById(userEntity);
        return Result.success();
    }


}
